﻿// Currency module JScript implementation file


////////////////////////////////////////////////////////////////////////
//// Objects, constants
////////////////////////////////////////////////////////////////////////

var CURRENCY_TAB_ID = "currency_tab";

// The object for currencies XML content
function CurrencyData() {
	this.date;			// the date of currency's value
	this.charCode;		// the character code of currency
	this.nominal;		// the nominal of currency
	this.value;			// the value of currency
	this.visible;		// marks to display current valute or not
	this.valuteId;		// unique ID for retrieving currency dynamic

	// displays currencies data
	this.getTableRow = function (rowNumber) {
		var row = "<tr class='" + ((rowNumber % 2 == 0) ? "even" : "odd") + "'>";
		row += "<td><a href='#' title='"+prefs.getMsg("dynamic")+":&nbsp;"+prefs.getMsg(this.charCode)+"' onclick='currencyReportLink_OnClick(\""+this.valuteId+"\",\""+this.date+"\",this.title); return false;'>";
		// adding images for USD and EURO
		if (this.charCode == "USD") {
			row += "<img height='11' weight='11' src='"+_IG_GetImageUrl("http://www.cbr.ru/images/icon_dollar.gif")+"'>";
		}
		else if (this.charCode == "EUR") {
			row += "<img height='11' weight='11' src='"+_IG_GetImageUrl("http://www.cbr.ru/images/icon_evro.gif")+"'>";
		}
		row += "<b>" + this.charCode + "</b>";
		// if nominal == 1 than it will not be displayed
		if (this.nominal != 1) {
			row += "&nbsp;(" + this.nominal + ")";
		}
		row += "</a></td>";
		row += "<td align='center'>" + this.date.substr(0,5) + "</td>";
		row += "<td align='right'><b>" + formatValueToRegStd(normalizeFloat(this.value, 4)) + "</b></td>";
		row += "<td id='"+this.charCode+"_difference' align='right'></td></tr>";

		return row;
	};
}


////////////////////////////////////////////////////////////////////////
//// Functions
////////////////////////////////////////////////////////////////////////

// Main function
function displayCurrencyInfo() {
	// Display loading status
	showLoadingInfo(CURRENCY_TAB_ID);
	var url = "http://www.cbr.ru/scripts/XML_daily.asp";
	// XML rate of exchange data
	_IG_FetchXmlContent(url, parseCurrencyXmlData);
}

// Function that parse currencies's database (XML)
function parseCurrencyXmlData(response) {
	if (responseError(response, CURRENCY_TAB_ID)) {
		return;
	}

	// Getting the date of rate
	var rateDate = response.getElementsByTagName("ValCurs").item(0).getAttribute("Date");

	// Get a list of the <Valute> element nodes in the file
	var itemList = response.getElementsByTagName("Valute");

	var currencies = new Array();

	// Loop through all <Valute> nodes
	for (var i = 0; i < itemList.length ; i++) {
		// For each <Valute> node, get child nodes.
		var nodeList = itemList.item(i).childNodes;

		currencies[i] = new CurrencyData();
		currencies[i].date = rateDate;
		// For each currency get its ValuteId
		var valuteId = itemList.item(i).getAttribute("ID");
		// Replacing TRY's valuteId R01700J with R01700 'couse there is a mistake in CBR's XML database
		if (valuteId != "R01700J") {
			currencies[i].valuteId = itemList.item(i).getAttribute("ID");
		}
		else {
			currencies[i].valuteId = "R01700";
		}

		// Loop through child nodes. Extract data from the text nodes that are
		// the children of the associated CharCode, Nominal, Value element nodes.
		for (var j = 0; j < nodeList.length ; j++) {
			var node = nodeList.item(j);

			switch (node.nodeName) {
				case "CharCode":
					currencies[i].charCode = node.firstChild.nodeValue;
					currencies[i].visible = prefs.getBool(currencies[i].charCode);
					break;
				case "Nominal":
					currencies[i].nominal = node.firstChild.nodeValue;
					break;
				case "Value":
					// replacing symbol "," with "." for conversion to float
					currencies[i].value = parseFloat(replaceCommaWithDot(node.firstChild.nodeValue));
					break;
			}
		}
	}   // eof looping through all <Valute> nodes

	// Moving USD and EURO to the first positions
	moveUsdAndEuroToTheTop(currencies);
	displayCurrencyData(currencies);

	// Tells gadget to resize itself
	_IG_AdjustIFrameHeight();

	// getting difference between rates of today and yesterday
	var url = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=" + formatDateForCbrf(getDateForNDaysAgo(rateDate, 1));
	_IG_FetchXmlContent(url, _IG_Callback(parseCurrencyXmlPastData, currencies));
} // eof parseCurrencyXmlData function

// Function that move USD and EURO with currencies that on the first place
function moveUsdAndEuroToTheTop(currencies) {
	for (var i = 2; i < currencies.length; i++) {
		if (currencies[i].charCode == "USD") {
			var tmp = currencies[0];
			currencies[0] = currencies[i];
			currencies[i] = tmp;
		}
		else if (currencies[i].charCode == "EUR") {
			var tmp = currencies[1];
			currencies[1] = currencies[i];
			currencies[i] = tmp;
		}
	}
}

// Function that parse currencies's database for one day ago (XML)
function parseCurrencyXmlPastData(response, currencies) {
	if (responseError(response, CURRENCY_TAB_ID)) {
		return;
	}

	var currenciesForOneDayAgo = new Array();

	// Get a list of the <Valute> element nodes in the file
	var itemList = response.getElementsByTagName("Valute");

	// Loop through all <Valute> nodes
	for (var i = 0; i < itemList.length ; i++) {
		// For each <Valute> node, get child nodes.
		var nodeList = itemList.item(i).childNodes;
		
		currenciesForOneDayAgo[i] = new CurrencyData();

		// Loop through child nodes. Extract data from the text nodes that are
		// the children of the associated CharCode, Value element nodes.
		for (var j = 0; j < nodeList.length ; j++) {
			var node = nodeList.item(j);

			switch (node.nodeName) {
				case "CharCode":
					currenciesForOneDayAgo[i].charCode = node.firstChild.nodeValue;
					break;
				case "Value":
					// replacing symbol "," with "." for conversion to float
					currenciesForOneDayAgo[i].value = parseFloat(replaceCommaWithDot(node.firstChild.nodeValue));
					break;
			}
		}
	}

	// Moving USD and EURO to the first positions
	moveUsdAndEuroToTheTop(currenciesForOneDayAgo);
	addDifferenceIntoCurrencyTable(currencies, currenciesForOneDayAgo);
} // eof gparseCurrencyXmlPastData function

// Funtion that adds the difference between rates of today and yesterday
function addDifferenceIntoCurrencyTable(currencies, currenciesForOneDayAgo) {
	for (var i = 0; i < currencies.length; i++) {
		if (currencies[i].visible) {
			var difference = currencies[i].value - currenciesForOneDayAgo[i].value;
			var diff_value = formatValueToRegStd(normalizeFloat(difference, 4));
			if (difference > 0) diff_value = "+" + diff_value;
			_gel(currencies[i].charCode + "_difference").innerHTML =
					"<div class='" + ((difference > 0) ? "increase" : "decrease") + "'>" + diff_value + "</div>";
		}
	}
}

// Function that displays main block of currencies
function displayCurrencyData(currencies) {
	// Display HTML string in <div>
	var copyright = "<div class='copyright'>" + 
										prefs.getMsg("copyright") + " <a href='http://www.cbr.ru' target='_blank'>http://www.cbr.ru</a>" + 
									"</div>";
	_gel(CURRENCY_TAB_ID).innerHTML = buildCurrencyTable(currencies) + copyright;
}

// Function that builds a table of currencies
function buildCurrencyTable(currencies) {
	var table = "<table class='rate_table'><thead>" + getCurrencyTableHeader() + "</thead><tbody>";
	// Building table body
	var rowNumber = 1;
	for (var i = 0; i < currencies.length; i++) {
		if (currencies[i].visible) {
			table += currencies[i].getTableRow(rowNumber);
			rowNumber++;
		}
	}
	table += "</tbody></table>";

	return table;
}

// Creating the header of output table
function getCurrencyTableHeader() {
	// Output table header
	return "<tr>" +
				"<td>" + prefs.getMsg("currency") + "</td>" +
				"<td>" + prefs.getMsg("date") + "</td>" +
				"<td>" + prefs.getMsg("rub_per_unit") + "</td>" +
				"<td>" + prefs.getMsg("change") + "</td>" +
		   "</tr>";
}

//Function that handles onclick event of initialize pop-up window link
function currencyReportLink_OnClick(valuteId, rateDate, title) {
	var dateFrom = formatDateForCbrf(getDateForNDaysAgo(rateDate, RATE_PERIOD));
	var dateTo = formatDateForCbrf(rateDate);

	//Function that retreive currencies dynamic from XML
	getCurDynamicByPeriod(valuteId, dateFrom, dateTo, title);
}

// Function that parsing and representing currency dynamic by period
// NOTE: Obtained dates should be in dd/mm/yyyy format
function getCurDynamicByPeriod(valuteId, dateFrom, dateTo, title) {
	var url = "http://www.cbr.ru/scripts/XML_dynamic.asp?date_req1=" + dateFrom + "&date_req2=" + dateTo + "&VAL_NM_RQ=" + valuteId;
	_IG_FetchXmlContent(url, _IG_Callback(parseCurrencyDynamicXml, title));
}

// Function that parse currencies dynamic (XML)
function parseCurrencyDynamicXml(response, title) {
	if (responseError(response, CURRENCY_TAB_ID)) {
		return;
	}

	var currencyDynamic = new Array();

	// Get a list of the <Record> element nodes in the file
	var itemList = response.getElementsByTagName("Record");
	// Loop through all <Record> nodes
	for (var i = 0; i < itemList.length ; i++) {
		currencyDynamic[i] = new RateDynamic();

		// For each <Record> node, get Date attribute.
		currencyDynamic[i].date = itemList.item(i).getAttribute("Date");

		// For each <Record> node, get child nodes.
		var nodeList = itemList.item(i).childNodes;

		// Loop through child nodes. Extract data from the text nodes that are
		// the children of the associated Value element nodes.
		for (var j = 0; j < nodeList.length ; j++) {
			var node = nodeList.item(j);
			if (node.nodeName == "Value") {
				// replacing symbol "," with "." for conversion to float
				currencyDynamic[i].value = replaceCommaWithDot(node.firstChild.nodeValue);
			}
		}
	}

	// This function will initialize pop-up window, create table and graph when we retreive currencies dynamic from XML
	CreateReportWindow(currencyDynamic, title);
}